import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import os
import random

np.random.seed(42)  # 设置随机种子，保证结果可重现

def generate_mock_data():
    # 创建输出目录
    output_dir = "mock_data"
    os.makedirs(output_dir, exist_ok=True)

    # 生成用户ID池 (1000个用户)
    user_ids = [f"user_{i}" for i in range(1, 1001)]

    # 生成日期范围 (7月1日至7月10日)
    date_range = [datetime(2025, 7, 1) + timedelta(days=i) for i in range(10)]

    # ========== 生成订单表数据数据 ==========
    order_info = []
    # 生成订单ID池 (1000个订单)
    order_ids = [f"order_{i}" for i in range(1, 1001)]
    # 定义订单状态列表
    ORDER_STATUSES = ["created", "paid", "shipped", "delivered", "cancelled"]
    # 定义产品类别列表
    PRODUCT_CATEGORIES = ["electronics", "clothing", "books", "home", "toys", "sports", "food", "beauty"]
    for date in date_range:
        # 每天随机选择600-800个用户生成订单
        daily_users = np.random.choice(user_ids, size=np.random.randint(600, 801), replace=False)
        for user in daily_users:
            order_id = np.random.choice(order_ids)
            # 随机生成访问时间 (当天的随机时间)
            order_time = date + timedelta(seconds=np.random.randint(0, 86400))
            status = random.choice(ORDER_STATUSES)
            category = random.choice(PRODUCT_CATEGORIES)
            amount = round(random.uniform(10.0, 1000.0), 2)
            quantity = random.randint(1, 10)
            # 为已取消订单设置退款金额
            refund_amount = amount if status == "cancelled" else 0.0

            order_info.append({
                "order_id": order_id,
                "user_id": user,
                "order_time": order_time.strftime("%Y-%m-%d %H:%M:%S"),
                "status": status,
                "category": category,
                "amount": amount,
                "quantity": quantity,
                "refund_amount": refund_amount
            })

    order_info = pd.DataFrame(order_info)
    order_info.to_csv(f"{output_dir}/order_info.csv", index=False)
    print(f"模拟数据已生成并保存到 '{output_dir}/order_info.csv' 目录下")

    # # ========== 生成进店访问数据 ==========
    # visit_records = []
    # for date in date_range:
    #     # 每天随机选择600-800个用户访问店铺
    #     daily_users = np.random.choice(user_ids, size=np.random.randint(600, 801), replace=False)
    #     for user in daily_users:
    #         # 随机生成访问时间 (当天的随机时间)
    #         visit_time = date + timedelta(seconds=np.random.randint(0, 86400))
    #         # 90%的访问来自无线端
    #         terminal_type = "wireless" if np.random.random() > 0.1 else "pc"
    #
    #         visit_records.append({
    #             "user_id": user,
    #             "visit_time": visit_time.strftime("%Y-%m-%d %H:%M:%S"),
    #             "terminal_type": terminal_type
    #         })
    #
    # visit_df = pd.DataFrame(visit_records)
    # visit_df.to_csv(f"{output_dir}/visit_data.csv", index=False)
    #
    # # ========== 生成短视频互动数据 ==========
    # video_interaction_records = []
    # for date in date_range:
    #     # 每天随机选择200-300个用户观看短视频
    #     daily_users = np.random.choice(user_ids, size=np.random.randint(200, 301), replace=False)
    #     for user in daily_users:
    #         # 随机生成观看时长 (0-10秒)
    #         watch_duration = np.random.randint(1, 11)
    #         # 随机生成互动类型 (like, comment, share)
    #         action_type = np.random.choice(["like", "comment", "share"], p=[0.7, 0.2, 0.1])
    #         # 95%的互动来自无线端
    #         terminal_type = "wireless" if np.random.random() > 0.05 else "pc"
    #
    #         interaction_time = date + timedelta(seconds=np.random.randint(0, 86400))
    #
    #         video_interaction_records.append({
    #             "user_id": user,
    #             "interaction_time": interaction_time.strftime("%Y-%m-%d %H:%M:%S"),
    #             "watch_duration": watch_duration,
    #             "action_type": action_type,
    #             "terminal_type": terminal_type
    #         })
    #
    # video_df = pd.DataFrame(video_interaction_records)
    # video_df.to_csv(f"{output_dir}/video_interaction_data.csv", index=False)
    #
    # # ========== 生成购物车支付数据 ==========
    # cart_payment_records = []
    # for date in date_range:
    #     # 每天随机选择100-150个用户进行支付
    #     daily_users = np.random.choice(user_ids, size=np.random.randint(100, 151), replace=False)
    #     for user in daily_users:
    #         # 是否为未进店直接支付 (30%概率)
    #         is_direct_payment = np.random.random() < 0.3
    #         # 95%的支付来自无线端
    #         terminal_type = "wireless" if np.random.random() > 0.05 else "pc"
    #
    #         payment_time = date + timedelta(seconds=np.random.randint(0, 86400))
    #
    #         cart_payment_records.append({
    #             "user_id": user,
    #             "payment_time": payment_time.strftime("%Y-%m-%d %H:%M:%S"),
    #             "is_direct_payment": is_direct_payment,
    #             "terminal_type": terminal_type
    #         })
    #
    # cart_df = pd.DataFrame(cart_payment_records)
    # cart_df.to_csv(f"{output_dir}/cart_payment_data.csv", index=False)
    #
    # # ========== 生成用户行为日志数据 ==========
    # action_records = []
    # page_types = {
    #     "shop_page": ["/shop/home", "/shop/category", "/shop/promotion"],
    #     "product_detail": ["/product/123", "/product/456", "/product/789"]
    # }
    #
    # for date in date_range:
    #     # 每个用户生成1-5次会话
    #     for user_id in user_ids:
    #         num_sessions = np.random.randint(1, 6)
    #         for _ in range(num_sessions):
    #             # 随机生成会话开始时间
    #             start_time = date + timedelta(
    #                 hours=np.random.randint(0, 24),
    #                 minutes=np.random.randint(0, 60),
    #                 seconds=np.random.randint(0, 60)
    #             )
    #
    #             # 随机生成会话停留时间 (10秒-30分钟)
    #             stay_time_seconds = np.random.exponential(scale=300)  # 指数分布，模拟多数短停留，少数长停留
    #             stay_time_seconds = max(10, min(stay_time_seconds, 1800))  # 限制在10秒到30分钟之间
    #
    #             # 随机生成会话内的操作次数 (1-20次)
    #             num_actions = np.random.randint(1, 21)
    #
    #             # 为会话生成操作记录
    #             for i in range(num_actions):
    #                 # 操作时间：随机会话内均匀分布
    #                 action_time = start_time + timedelta(seconds=int(stay_time_seconds * i / num_actions))
    #
    #                 # 随机选择页面类型和URL
    #                 page_type = np.random.choice(["shop_page", "product_detail"], p=[0.3, 0.7])
    #                 page_url = np.random.choice(page_types[page_type])
    #
    #                 # 随机选择操作类型
    #                 action_type = np.random.choice(["click", "view", "add_cart", "buy"])
    #
    #                 action_records.append({
    #                     "user_id": user_id,
    #                     "page_url": page_url,
    #                     "action_time": action_time.strftime("%Y-%m-%d %H:%M:%S"),
    #                     "action_type": action_type
    #                 })
    #
    # action_df = pd.DataFrame(action_records)
    # action_df.to_csv(f"{output_dir}/user_action_log.csv", index=False)
    #
    # # ========== 生成页面分类字典数据 ==========
    # page_mapping_records = []
    # for page_type, urls in page_types.items():
    #     for url in urls:
    #         page_mapping_records.append({
    #             "page_url": url,
    #             "page_type": page_type
    #         })
    #
    # page_mapping_df = pd.DataFrame(page_mapping_records)
    # page_mapping_df.to_csv(f"{output_dir}/page_mapping.csv", index=False)
    # print(f"模拟数据已生成并保存到 '{output_dir}' 目录下")

# 生成模拟订单数据
def generate_orders_data(n=1000):
    # 生成用户ID池 (1000个用户)
    user_ids = [f"user_{i}" for i in range(1, 1001)]

    # 订单ID
    order_ids = [f"order_{i}" for i in range(1, n + 1)]

    # 随机选择买家ID，允许重复（模拟复购）
    user_list = np.random.choice(user_ids, n)

    # 支付状态：80%成功，20%失败
    payment_status = np.random.choice(
        ["SUCCESS", "FAILED"],
        n,
        p=[0.8, 0.2]
    )

    # 支付时间：过去30天内随机时间
    base_date = datetime.now() - timedelta(days=30)
    payment_times = [
        base_date + timedelta(seconds=np.random.randint(0, 30 * 24 * 60 * 60))
        for _ in range(n)
    ]

    # 是否预售：10%概率是预售订单
    is_presale = np.random.choice([True, False], n, p=[0.1, 0.9])

    # 预售尾款支付时间（仅对预售订单有效）
    presale_final_payment_times = []
    for i in range(n):
        if is_presale[i] and payment_status[i] == "SUCCESS":
            # 尾款支付时间在定金支付后1-7天
            delta = timedelta(days=np.random.randint(1, 8))
            presale_final_payment_times.append(payment_times[i] + delta)
        else:
            presale_final_payment_times.append(None)

    # 创建DataFrame
    orders_df = pd.DataFrame({
        "order_id": order_ids,
        "user_id": user_list,
        "payment_status": payment_status,
        "payment_time": payment_times,
        "is_presale": is_presale,
        "presale_final_payment_time": presale_final_payment_times
    })

    return orders_df


# 生成模拟退款数据
def generate_refunds_data(orders_df):
    # 只对支付成功的订单生成退款
    success_orders = orders_df[orders_df["payment_status"] == "SUCCESS"]

    # 5%的订单会退款
    refunded_orders = success_orders.sample(frac=0.05)

    refund_ids = [f"refund_{i}" for i in range(1, len(refunded_orders) + 1)]

    # 退款类型：售中退款(确认收货前)占70%，售后退款占30%
    refund_types = np.random.choice(
        ["PRESALE_REFUND", "AFTER_SALE_REFUND"],
        len(refunded_orders),
        p=[0.7, 0.3]
    )

    # 退款时间：支付成功后1-30天内
    refund_times = []
    for _, row in refunded_orders.iterrows():
        # 对于预售订单，使用尾款支付时间
        payment_time = row["presale_final_payment_time"] or row["payment_time"]
        delta = timedelta(days=np.random.randint(1, 31))
        refund_times.append(payment_time + delta)

    # 创建退款DataFrame
    refunds_df = pd.DataFrame({
        "refund_id": refund_ids,
        "original_order_id": refunded_orders["order_id"].tolist(),
        "user_id": refunded_orders["user_id"].tolist(),
        "refund_type": refund_types,
        "refund_time": refund_times
    })

    return refunds_df

if __name__ == "__main__":
    generate_mock_data()

    # # 生成10000条订单数据
    # orders = generate_orders_data(10000)
    #
    # # 生成退款数据
    # refunds = generate_refunds_data(orders)
    #
    # # 保存数据
    # orders.to_csv("mock_data/orders_2.csv", index=False)
    # refunds.to_csv("mock_data/refunds_2.csv", index=False)
    #
    # print(f"已生成 {len(orders)} 条订单数据和 {len(refunds)} 条退款数据")
    # print("数据已保存为 orders_2.csv 和 refunds_2.csv")